﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MVC.Models;
using MVC.Models.Database;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MVC.Controllers
{
    public class AdminController : Controller
    {
        private readonly LifengContext _context;
        public AdminController(LifengContext context)
        {
            _context = context;
        }
        [Route("/[controller]")]
        public IActionResult index()
        {
            return View();
        }

        [HttpPost]
        [Route("/api/admin/login")]
        public IActionResult AdminL(AdminLog request)
        {
            // return Json(request);
            // 如果用户名和密码正确返回登录成功
            if (_context.Admins.Where(u => u.AdminName == request.AdminName && u.AdminPassword == request.AdminPassword).Count() > 0)
            {
                // 登录成功后设置cookie
                var claims = new List<Claim>
                {
                new Claim(ClaimTypes.Name, request.AdminName),
                new Claim(ClaimTypes.Thumbprint, request.AdminPassword),
                };
                HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
                return Json(new { status = "success", data = request.AdminName, msg = "登录成功" });
            }
            return Json(new { status = "fail", data = "登录失败" });
            //存在的话 走登录流程
        }

    }
}
